package com.s51.no4_listview;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        initView();
    }
    private void initView(){
        ListView listView = findViewById(R.id.listview);
        listView.setAdapter(new MyAdapter());
    }
    /** 商品类 **/
    class Goods{
        //商品名称 信息
        private String name,message;
        //商品图片ID
        private int icon;

        private ImageView imageView;
        TextView tvname,tvmessage;
        Goods(String name,String message,int icon){
            this.name = name;
            this.message=message;
            this.icon = icon;
        }
        public void setView(View view){
            if(imageView==null)
                imageView = view.findViewById(R.id.image);
            if(tvname==null)
                tvname=view.findViewById(R.id.name);
            if(tvmessage==null)
                tvmessage = view.findViewById(R.id.message);
            imageView.setImageResource(icon);
            tvname.setText(name);
            tvmessage.setText(message);
        }
    }
    Goods[] goods={
            new Goods("苹果","10元/kg",R.drawable.apple),
            new Goods("桌子","1800元",R.drawable.table),
            new Goods("蛋糕","300元",R.drawable.cake),
            new Goods("线衣","210元",R.drawable.wireclothes),
            new Goods("猕猴桃","10元/kg",R.drawable.kiwifruit),
            new Goods("围巾","50元",R.drawable.scarf),
    };
    class MyAdapter extends BaseAdapter{

        @Override
        public int getCount() {
            return goods.length;
        }

        @Override
        public Object getItem(int i) {
            return goods[i];
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            if(view==null)
                view = View.inflate(MainActivity.this,R.layout.item,null);
            goods[i].setView(view);
            return view;
        }
    }
}